<?php

declare(strict_types=1);

namespace app\admin\model;

use think\Model;

class Department extends BaseModel
{
    // 定义数据表名
    protected $name = 'department';

    // 定义主键
    protected $primaryKey = 'id';

    // 定义创建时间字段名
    protected $createTime = 'create_time';

    // 定义更新时间字段名
    protected $updateTime = 'update_time';
    // 定义自动时间戳
    protected $autoWriteTimestamp = true;

    // 设置字段信息
    protected $schema = [
        'id'          => 'int',
        'pid'         => 'int',
        'name'        => 'string',
        'status'      => 'int',
        'remark'      => 'string',
        'create_time' => 'datetime',
        'creator'     => 'int',
        'update_time' => 'datetime',
        'updater'     => 'int',
        'is_del'      => 'int',
    ];



    // 定义一个通用的访问器来获取属性值
    protected $attributes = [
        'status' => [
            0 => '开启',
            1 => '禁用'
        ]
    ];


    public function getFieldEnum($field)
    {

        if ('ALL' === strtoupper($field)) {
            return [
                'gender' => $this->attributes['gender'],
                'level' => $this->attributes['level'],
                'decision' => $this->attributes['decision'],
            ];
        } else {
            return [$field => $this->$field];
        }
    }

    public function parentDepartment()
    {
        return $this->belongsTo(Department::class, 'pid', 'id');
    }

    /**
     * @describe 获取下拉框格式数据
     * @author: Bobo
     * @date: 2024-08-23 10:06:27
     * @param [type] @required
     * @return Renderable
     */
    public function getTreeSelectOption(array $where, $fields = 'id, pid, name')
    {

        $data = $this
            ->field($fields)
            ->where($where)
            ->select()
            ->toArray();
        foreach ($data as &$option) {
            if (!isset($option['children'])) {
                $children = $this->getTreeSelectOption(['is_del' => 0, 'status' => 1, 'pid' => $option['id']]);
                if (!empty($children)) {
                    $option['children'] = $children;
                } else {
                    $option['children'] = [];
                }
            }
        }

        return $data;
    }


    public function getAllDepartmentId($parent_id, $where = ['is_del' => 0, 'status' => 1], &$result = [])
    {
        $result[] = $parent_id;
        $children = $this->where($where)->where('pid', $parent_id)->column('id');
        foreach ($children as $child) {

            $this->getAllDepartmentId($child,  $where, $result);
        }
        return $result;
    }
}
